import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io' show Platform;

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    var theme = Theme.of(context);
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: theme.scaffoldBackgroundColor, // 状态栏背景颜色
      statusBarIconBrightness: theme.brightness == Brightness.dark
          ? Brightness.light // 如果是深色主题，图标为亮色
          : Brightness.dark, // 如果是浅色主题，图标为暗色
    ));
    return MaterialApp(
      title: 'iOS AI',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const WebViewScreen(),
    );
  }
}

class WebViewScreen extends StatefulWidget {
  const WebViewScreen({super.key});

  @override
  State<WebViewScreen> createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  late final InAppWebViewController _controller;

  @override
  void initState() {
    super.initState();
    // 初始化逻辑转移到 WebView 属性中
    requestPermissions();
  }

  Future<void> requestPermissions() async {
    await [
      Permission.camera,
      Permission.microphone,
      Permission.storage,
      Permission.speech
    ].request();
  }

  Future<void> _launchURL(String url) async {
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {
      throw 'Could not launch $url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final canGoBack = await _controller.canGoBack();
        if (canGoBack) {
          _controller.goBack();
        }

        // 允许关闭页面
        return !canGoBack;
      },
      child: Scaffold(
        body: SafeArea(
          top: true,
          child: InAppWebView(
            initialUrlRequest: URLRequest(
              url: WebUri.uri(
                  Uri.parse('https://gpt.xauat.site/')), // 替换为你的网站URL
            ),
            initialSettings: InAppWebViewSettings(
              javaScriptEnabled: true,
              mediaPlaybackRequiresUserGesture: false,
              databaseEnabled: true,

              // Android 专属
              useHybridComposition: true,
              allowFileAccess: true,
              allowContentAccess: true,
              domStorageEnabled: true,
              // 启用本地存储

              allowsInlineMediaPlayback: true,
              allowsBackForwardNavigationGestures: true,
            ),
            onWebViewCreated: (controller) {
              _controller = controller;
            },
            shouldOverrideUrlLoading: (controller, request) async {
              if ((Platform.isLinux ||
                      Platform.isMacOS ||
                      Platform.isWindows) &&
                  request.request.url != null &&
                  (request.request.url!.host != "gpt.xauat.site" && request.request.url!.host != "casdoor.xauat.site")) {
                // 如果是外部链接，使用浏览器打开
                await _launchURL(request.request.url.toString());
                return NavigationActionPolicy.CANCEL; // 取消 WebView 加载该链接
              }
              return NavigationActionPolicy.ALLOW; // 允许 WebView 加载该链接
            },
            onPermissionRequest: (controller, request) async {
              return PermissionResponse(
                resources: request.resources,
                action: PermissionResponseAction.GRANT,
              );
            },
          ),
        ),
      ),
    );
  }
}
